# coding=utf-8
'''
Created on 2012-6-30

@author: wb_suoyao.shen
'''
import os
import datetime
import uuid
import logging
from django.utils import simplejson
from django.shortcuts import get_object_or_404
from django.views.decorators.csrf import csrf_exempt
from django.http import HttpResponse
from django.shortcuts import render_to_response
from ssyblog.diary.models import Diary
from ssyblog.tags.models import Tags
from ssyblog.diary.forms import TagForm
from ssyblog.diary.forms import DiaryForm
from django.core.paginator import Paginator,InvalidPage,EmptyPage,PageNotAnInteger
from ssyblog.common import constant
from ssyblog import settings

logger = logging.getLogger('main')

def addDiary(request):
    tags_list = Tags.objects.all()
    nav_parent = 'Diary Manage'
    nav_child = 'New Diary'
    current_nav = 'add_diary'
    return render_to_response('cms/diarys/diary_add.html', locals())

def queryDiary(request):
    try:
        page = int(request.GET.get('page','1'))
        if page < 1:
            page = 1
    except ValueError:
        page = 1
    diary_list = Diary.objects.query_by_condition()
    paginator = Paginator(diary_list, constant.pre_page_number)
    try:
        diarylist = paginator.page(page)
    except (InvalidPage,PageNotAnInteger):
        # if page is not a Integer or Invalid, return page one.
        diarylist = paginator.page(1)
    except EmptyPage:
        # if page is empty, return last page.
        diarylist = paginator.page(paginator.num_pages)
    nav_parent = 'Diary Manage'
    nav_child = 'Diary Query'
    current_nav = 'diary_query'
    return render_to_response('cms/diarys/diary_query.html', {'diarylist':diarylist, 'nav_parent':nav_parent, 'nav_child':nav_child, 'current_nav':current_nav, 'paginator':paginator})

def queryComment(request):
    nav_parent = 'Diary Manage'
    nav_child = 'Comment Query'
    current_nav = 'comment_query'
    return render_to_response('cms/diarys/comment_query.html', locals())

@csrf_exempt
def saveDiary(request):
    if request.method == 'POST':
        form = DiaryForm(request.POST)
        if form.is_valid():
            obj = form.save(commit=False)
            try:
                obj.author = request.session['user']
            except KeyError:
                obj.author = ''
            obj.write_time = datetime.datetime.now()
            obj.modify_time = datetime.datetime.now()
            obj.reply_count = 0
            obj.status = 'on'
            obj.recommend = 'off'
            obj.save()
    else:
        form = TagForm()
    tags_list = Tags.objects.all()
    nav_parent = 'Diary Manage'
    nav_child = 'New Diary'
    current_nav = 'add_diary'
    tips = '添加日志成功'
    return render_to_response('cms/diarys/diary_add.html',locals())

def editDiary(request,diaryId):
    if diaryId:
        diary = Diary.objects.get(pk=diaryId)
    tags_list = Tags.objects.all()
    nav_parent = 'Diary Manage'
    nav_child = 'Diary Query'
    current_nav = 'diary_query'
    return render_to_response('cms/diarys/diary_edit.html',locals())

@csrf_exempt
def updateDiary(request,diaryId):
    diary_to_update = get_object_or_404(Diary, pk = diaryId)
    form = DiaryForm(request.POST,instance = diary_to_update)
    if form.is_valid():
        obj = form.save(commit=False)
        obj.modify_time = datetime.datetime.now()
        obj.save()
    return queryDiary(request)

def deleteDiary(request,diaryId):
    if diaryId:
        Diary.objects.get(pk=diaryId).delete()
    return queryDiary(request)

def recommendDiary(request,diaryId):
    if diaryId:
        diary = Diary.objects.get(pk = diaryId)
        diary.recommend = 'on'
        diary.save()
    return queryDiary(request)

@csrf_exempt
def uploadFile(request,*args):
    if request.method == 'POST':
        upload = request.FILES['imgFile']
        result = {}
        try :
            file_ext = str(upload.name).split('.')[-1].lower()
            upload_folder = settings.MEDIA_DIARY_ROOT
            file_name = str(uuid.uuid1()) + '.' + file_ext
            iamge_path = upload_folder + file_name
            if not os.path.exists(upload_folder):
                os.mkdir(upload_folder)
            dest = open(iamge_path,'wb+')
            for block in upload.chunks():
                dest.write(block)
            dest.close()
            result['error'] = 0
            result['url'] = '/diary_images/' + file_name
        except IOError:
            logger.info('upload images failed:[%s]' % IOError.message)
            result['error'] = 1
            result['message'] = 'upload images failed:[%s]' % IOError.message
    return HttpResponse(simplejson.dumps(result),mimetype='application/json')
